package com.fll.codeworld.util;

import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author zhaotao
 * @description 对称加解密
 * @date 2021/5/6 15:15
 */
public class AESUtils {

    private static Cipher cipher;
    static{
        try{
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        }catch(Exception e){

        }
    }
    /**
     * AES解密
     * @param encryptStr 密文
     * @param decryptKey 秘钥，必须为16个字符组成
     * @return 明文
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
        if (StringUtils.isEmpty(encryptStr) || StringUtils.isEmpty(decryptKey)) {
            return null;
        }
        byte[] encryptByte = Base64.getDecoder().decode(encryptStr);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptByte);
        return new String(decryptBytes);
    }

    /**
     * AES加密
     * @param content 明文
     * @param encryptKey 秘钥，必须为16个字符组成
     * @return 密文
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        if (StringUtils.isEmpty(content) || StringUtils.isEmpty(encryptKey)) {
            return null;
        }

        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));

        byte[] encryptStr = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptStr);
    }

    /**
     * 测试加密与解密
     * @param args
     */
    public static void main(String[] args) {
        try {
            //加密
            String s1 = "123456";
            String id = "ce870f73d94f42a3a5d8d681c2fb917d";
            String encryptKey = id.substring(0,16);
            System.out.println(AESUtils.aesEncrypt(s1, encryptKey));

            //解密
            String secretKey = "4d1db42a1aee4545810d11222bcca8b1";
            secretKey = secretKey.substring(0,16);
            String content = "zoNuerqeVZWEUE6vT9uhlA==";
            System.out.println(aesDecrypt(content, secretKey));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
